package com.yq.tanhua.ui.login

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.Group
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.fmt.mvi.learn.gobal.log
import com.gyf.immersionbar.ImmersionBar
import com.yq.tanhua.R
import com.yq.tanhua.ui.TanHuaBaseActivity
import com.yq.tanhua.ui.login.viewmodel.LoginViewModel
import config.TanHua_login
import config.TanHua_main
import config.TanHua_settting_info
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@OptIn(ExperimentalMaterial3Api::class)
@Route(path = TanHua_login)
@AndroidEntryPoint
class LoginActivity : TanHuaBaseActivity() {

    val viewModel: LoginViewModel by viewModels()

    var phone by mutableStateOf("18600887431")

    @SuppressLint("StateFlowValueCalledInComposition")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImmersionBar.with(this).transparentBar().init()
        setContent {
            Content()
        }
    }

    fun getPhoneCode(phone: String) {
        viewModel.viewModelScope.launch {
            viewModel.userIntent.emit(LoginViewAction.SendMsgCode(phone))
        }
    }

    @Composable
    fun Content() {
        val state = viewModel.state.collectAsState()

        Column(horizontalAlignment = Alignment.Start, modifier = Modifier.fillMaxWidth(1f)) {
            Image(
                painter = painterResource(id = R.drawable.login_bg),
                contentDescription = "hhhh",
                modifier = Modifier.fillMaxWidth(1f),
                contentScale = ContentScale.FillWidth
            )
            when (state.value) {
                is LoginViewState.VerifySucess -> {
                    val new = (state.value as LoginViewState.VerifySucess).isNew
                    if (new) {
                        ARouter.getInstance().build(TanHua_settting_info).navigation()
                    } else {
                        ARouter.getInstance().build(TanHua_main).navigation()
                    }

                    finish()
                }

                is LoginViewState.VerifyFail, LoginViewState.Success -> {
                    VerifyMsgCodeView(state = state)
                }

                else -> {
                    SendMsgView(state)
                }
            }
        }
    }


    @Composable
    fun SendMsgView(state: State<LoginViewState?>) {

        var selectNumber by remember {
            mutableStateOf(0)
        }
        Row(verticalAlignment = Alignment.CenterVertically) {
            RadioButton(selected = selectNumber == 0, onClick = {
                selectNumber = 0
                phone = "18600887431"
            })
            Text(text = "18600887431")

            RadioButton(selected = selectNumber == 1, onClick = {
                selectNumber = 1
                phone = "13500000000"
            })
            Text(text = "13500000000")
        }
        Row {

        }

        Text(
            text = "请输入手机号",
            style = TextStyle(color = Color.Black, fontWeight = FontWeight.Bold),
            modifier = Modifier.padding(top = 60.dp, start = 20.dp),
            fontSize = 20.sp
        )
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(top = 30.dp)
        ) {
            Text(text = "+86", modifier = Modifier.padding(start = 20.dp, end = 8.dp))
            TextField(
                value = phone,
                onValueChange = { newText ->
                    phone = newText
                    newText.log()
                },
                label = { Text(text = "请输入手机号") },
                colors = TextFieldDefaults.textFieldColors(
                    containerColor = Color.White,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent
                ),
                modifier = Modifier.fillMaxWidth(1f)
            )
        }
        Spacer(
            modifier = Modifier
                .padding(horizontal = 20.dp, vertical = 3.dp)
                .height(0.6.dp)
                .background(Color.Gray)
                .fillMaxWidth(1f)

        )
        val statusText = if (state.value == LoginViewState.Loading) {
            "请求中"
        } else if (state.value == LoginViewState.Fail) {
            "获取验证码失败"
        } else {
            "获取验证码"
        }
        Button(
            enabled = state.value != LoginViewState.Loading,
            onClick = {
                getPhoneCode(phone)
            }, modifier = Modifier
                .padding(horizontal = 20.dp, vertical = 40.dp)
                .fillMaxWidth(1f)
        ) {
            Text(text = statusText, style = TextStyle(color = Color.White))
        }

    }

    @Composable
    fun VerifyMsgCodeView(state: State<LoginViewState?>) {
        var text by remember { mutableStateOf(TextFieldValue("")) }
        LaunchedEffect(null) {
            viewModel.viewEvent.collect {
                when (it) {
                    is LoginViewModel.LoginViewEvent.ShowVerifyFail -> {
                        showToast(it.msg)
                        text = text.copy(text = "")
                    }
                }

            }
        }


        Text(
            text = "输入六位验证码",
            style = TextStyle(color = Color.Black, fontWeight = FontWeight.Bold),
            modifier = Modifier.padding(top = 60.dp, start = 20.dp),
            fontSize = 20.sp
        )
        Text(
            text = "已经发送到: $phone",
            fontSize = 19.sp,
            modifier = Modifier.padding(top = 10.dp, start = 20.dp),
        )
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(top = 30.dp)
        ) {
            TextField(
                value = text,
                label = { Text(text = "输入123456后自动校验") },
                onValueChange = { newText ->
                    text = newText
                    newText.log()
                    if (text.text.length >= 6) {
                        viewModel.viewModelScope.launch {
                            viewModel.userIntent.emit(
                                LoginViewAction.VerifyMsgCode(
                                    text.text,
                                    phone
                                )
                            )
                        }
                    }
                },
                colors = TextFieldDefaults.textFieldColors(
                    containerColor = Color.White,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent
                ),
                modifier = Modifier.fillMaxWidth(1f)
            )
        }
        Spacer(
            modifier = Modifier
                .padding(horizontal = 20.dp, vertical = 3.dp)
                .height(0.6.dp)
                .background(Color.Gray)
                .fillMaxWidth(1f)

        )
        Button(
            onClick = {
                showToast("bingZgo")
            }, modifier = Modifier
                .padding(horizontal = 20.dp, vertical = 40.dp)
                .fillMaxWidth(1f)
        ) {
            Text(text = "重新发送（60）", style = TextStyle(color = Color.White))
        }
    }

    fun showToast(msg: String) {
        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
    }

}